<template>
  <div class="app-container towSearchHeader">
    <div class="customContainer">
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select class="w160" filterable placeholder="选择门店" v-model="formInline.store_id" style="width:300px">
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker @change="getData" :editable="false" :clearable="false" v-model="pickerDate" value-format="yyyy.MM.dd" type="daterange" align="right"
            unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" style="width:240px">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 进度条 -->
      <DJprogress :progressData="firProgressData" :title="firTitle"></DJprogress>
      <DJprogress :progressData="secProgressData" :title="secTitle" :color="secColor"></DJprogress>
      <DJprogress :progressData="thiProgressData" :title="thiTitle" :color="thiColor"></DJprogress>
      <br />
      <br />
      <hr class="DJhr" />
      <br />
      <p class="chartTitle">门店营业额趋势图</p>

      <el-row style="background:#fff;margin:32px 0;">
        <div class="legend">
          <div class="legend-item" @click="changeSelect('考核值')" :class="{'legend-fir':selectedData['考核值']}">
            <div class="legend-line"></div>
            <div class="legend-circle"></div>
            <span>考核值</span>
          </div>
          <div class="legend-item" @click="changeSelect('实际完成值')" :class="{'legend-sec':selectedData['实际完成值']}">
            <div class="legend-line"></div>
            <div class="legend-circle"></div>
            <span>实际完成值</span>
          </div>
          <el-tooltip content="请调整时间维度为7天后查看近七日对比数据" placement="bottom" effect="light" :disabled="isSenve">
            <div class="legend-item" @click="changeSelect('近七日对比')" :class="{'legend-thi':selectedData['近七日对比'],'disabled':!isSenve}">
              <div class="legend-line"></div>
              <div class="legend-circle"></div>
              <span>近七日对比</span>
            </div>
          </el-tooltip>
        </div>
        <line-chart :chart-data="lineChartData" :selectedData="selectedData" :showLegend="showLegend" :legendData="legendData" :prevSevenDate="sevenDate" />
      </el-row>

      <p class="chartTitle">门店今日实时营收汇总表</p>
      <el-row class="table-nav">
        <el-col class="nav-item" :span="6">
          <div :class="{show:showItem==0}" @click="changeTableNav(0)">售币类</div>
          <div :class="{show:showItem==1}" @click="changeTableNav(1)">门禁类</div>
          <div :class="{show:showItem==2}" @click="changeTableNav(2)">其他类</div>
          <div :class="{show:showItem==3}" @click="changeTableNav(3)">小程序核销</div>
        </el-col>
        <el-col :span="6" :offset="12" style="text-align:right">
          <el-button type="primary" size="small" @click="jumpRevenueAnalysis_all_form">查看历史明细</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table v-if="showItem!=3" highlight-current-row :data="belowList" v-loading.body="listLoading" border show-summary fit :summary-method="getSummaries"
        size="small">
        <el-table-column align="center" label="种类" prop="name"></el-table-column>
        <el-table-column align="center" label="笔数" prop="time" sortable></el-table-column>
        <el-table-column align="center" label="笔数占比" prop="timeRatio" sortable sort-by="time"></el-table-column>
        <el-table-column align="center" label="金额（元）" prop="money" sortable></el-table-column>
        <el-table-column align="center" label="金额占比" prop="moneyRatio" sortable sort-by="money"></el-table-column>
      </el-table>
      <p v-else style="text-align:center;">小程序今日实时核销金额：{{verification_money}}元</p>
    </div>
  </div>
</template>

<script>
import DJprogress from './components/DJprogress';
import LineChart from './components/LineChart';
import { pickerOptionsF, pickerDateSevenDays, optionMaxTime, isSevenDays } from '@/utils';
import { getTodayData, getTimeSlotData, getStoreList, sevenData, coinList, accessList, otherList } from '@/api/dashboard/revenueStatistics';

export default {
  components: {
    DJprogress,
    LineChart
  },
  data() {
    return {
      verification_money:0,
      firTitle: '今天',
      secTitle: '本月',
      thiTitle: '区间',
      secColor: 'yellow',
      thiColor: 'blue',
      firProgressData: {
        TargetValue: '0',
        value: '0'
      },
      secProgressData: {
        TargetValue: '0',
        value: '0'
      },
      thiProgressData: {
        TargetValue: '0',
        value: '0'
      },
      listLoading: false,
      showLegend: false,
      isSenve: true,
      showItem: 0,
      prevStoreId: 0,
      storeList: null,
      belowList: [],
      selectedData: {
        考核值: true,
        实际完成值: true,
        近七日对比: false
      },
      formInline: {
        store_id: '',
        start_time: '',
        end_time: '',
        look_del: '0'
      },
      lineChartData: {
        dimensions: ['product', '考核值', '实际完成值', '近七日对比'],
        source: []
      },
      legendData: ['考核值', '实际完成值', '近七日对比'],
      sevenDate: [],
      pickerOptions: pickerOptionsF(),
      pickerDate: pickerDateSevenDays()
    };
  },
  activated() {
    if (this.$route.params.store_id || !this.storeList) {
      if (this.$route.params.store_id) {
        this.pickerDate = pickerDateSevenDays(-7, -1);
      }
      this.getData();
      this.getStore();
    }
  },
  methods: {
    handleSetLineChartData(type) {
      this.lineChartData = lineChartData[type];
    },
    changeSelect(key) {
      if (key === '近七日对比' && this.isSenve == false) return;
      if (this.selectedData[key]) this.selectedData[key] = false;
      else this.selectedData[key] = true;
    },
    getData() {
      optionMaxTime(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.start_time = this.pickerDate ? this.pickerDate[0] : '';
        this.formInline.end_time = this.pickerDate ? this.pickerDate[1] : '';
        if (isSevenDays(this.pickerDate)) {
          this.isSenve = true;
        } else {
          this.isSenve = false;
        }
      });
    },
    //切换展示类型
    changeTableNav(i) {
      this.showItem = i;
      this.belowList = [];
      if (i == 0) {
        this.getCoinList();
      } else if (i == 1) {
        this.getAccessList();
      } else if (i == 2) {
        this.getOtherList();
      }
    },
    searchClick() {
      if (this.prevStoreId == this.formInline.store_id) this.getLineData();
      else {
        this.belowList = [];
        this.showItem = 0;
        this.fetchData();
        this.getCoinList();
      }
    },
    // 门店列表获取
    getStore() {
      this.listLoading = true;
      getStoreList({
        look_del: this.formInline.look_del,
        category_id: 404
      }).then(response => {
        this.storeList = response;
        let data = response.filter(res => res.id == this.$store.getters.optionId);
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        } else {
          if (this.storeList.length > 0) {
            this.formInline.store_id = this.storeList[0].id;
          }
        }
        if (this.$route.params.store_id) {
          this.formInline.store_id = this.$route.params.store_id;
        }
        this.belowList = [];
        this.fetchData();
        this.getCoinList();
      });
    },
    fetchData() {
      getTodayData({ store_id: this.formInline.store_id }).then(res => {
        this.prevStoreId = this.formInline.store_id;
        if (res.code == 1) {
          //今日数据
          this.firProgressData.TargetValue = (res.data.today_actual_turnover.target_turnover / 100).toFixed(2);
          this.firProgressData.value = (res.data.today_actual_turnover.actual_turnover / 1).toFixed(2);
          this.verification_money=(res.data.wx_today.wx_money / 1).toFixed(2);
          //本月数据
          this.secProgressData.TargetValue = (res.data.month_actual_turnover.target_turnover / 100).toFixed(2);
          this.secProgressData.value = (res.data.month_actual_turnover.actual_turnover / 1).toFixed(2);
          this.getLineData();
        }
      });
    },
    //获取当前时间段和折线图数据
    getLineData() {
      getTimeSlotData({
        store_id: this.formInline.store_id,
        begin_time: this.pickerDate[0],
        end_time: this.pickerDate[1]
      })
        .then(res => {
          let currentDates = new Date(this.pickerDate[1].replace(/\./g, '-')) - new Date(this.pickerDate[0].replace(/\./g, '-'));
          currentDates /= 1000 * 60 * 60 * 24;
          if (res.code == 1) {
            this.selectedData['考核值'] = true;
            this.selectedData['实际完成值'] = true;
            this.selectedData['近七日对比'] = false;
            let weekday = [' 周日', ' 周一', ' 周二', ' 周三', ' 周四', ' 周五', ' 周六'];
            this.lineChartData.source = [];
            if (res.data.list.length == 0) {
              this.thiProgressData.TargetValue = this.firProgressData.TargetValue;
              this.thiProgressData.value = this.firProgressData.value;
              let weekIndex = new Date().getDay();
              this.lineChartData.source.unshift({
                product: this.pickerDate[0].replace(/\./g, '-') + weekday[weekIndex],
                考核值: this.thiProgressData.TargetValue,
                实际完成值: this.thiProgressData.value
              });
              return;
            }
            //当前时间段数据
            this.thiProgressData.TargetValue = (res.data.total.target_turnover / 100).toFixed(2);
            this.thiProgressData.value = res.data.total.actual_turnover.toFixed(2);
            let now = new Date().toLocaleDateString().split('/');
            if (now[1] / 1 < 10) now[1] = '0' + now[1];
            if (now[2] / 1 < 10) now[2] = '0' + now[2];
            now = now.join('.');
            if (now == this.pickerDate[1]) {
              this.thiProgressData.TargetValue = (this.firProgressData.TargetValue / 1 + this.thiProgressData.TargetValue / 1).toFixed(2);
              this.thiProgressData.value = (this.firProgressData.value / 1 + this.thiProgressData.value / 1).toFixed(2);
            }

            for (let val of res.data.list) {
              let weekIndex = new Date(val.time).getDay();
              this.lineChartData.source.unshift({
                product: val.time + weekday[weekIndex],
                考核值: (val.target_turnover / 100).toFixed(2),
                实际完成值: (val.actual_turnover / 1).toFixed(2)
              });
            }
            if (res.data.list.length == currentDates) {
              let date = this.pickerDate[1].replace(/\./g, '-');
              let weekIndex = new Date(date).getDay();
              this.lineChartData.source.push({
                product: date + weekday[weekIndex],
                考核值: this.firProgressData.TargetValue,
                实际完成值: this.firProgressData.value
              });
            }
            if (this.isSenve) {
              sevenData({
                store_id: this.formInline.store_id,
                begin_time: this.pickerDate[0],
                end_time: this.pickerDate[1]
              }).then(sevenRes => {
                if (sevenRes.code == 1) {
                  this.sevenDate = [];
                  for (let i in sevenRes.data.list) {
                    this.lineChartData.source[6 - i]['近七日对比'] = (sevenRes.data.list[i].actual_turnover / 1).toFixed(2);
                    let date = sevenRes.data.list[i].time;
                    let weekIndex = new Date(date).getDay();
                    this.sevenDate.unshift(date + weekday[weekIndex]);
                  }
                }
                this.listLoading = false;
              });
            } else {
              this.listLoading = false;
            }
          }
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    //获取售币类列表
    getCoinList() {
      this.listLoading = true;
      coinList({ store_id: this.formInline.store_id })
        .then(res => {
          if (res.list) {
            this.getBelowList(res.list, 0);
          }
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    //获取门禁类列表
    getAccessList() {
      this.listLoading = true;
      accessList({ store_id: this.formInline.store_id })
        .then(res => {
          if (res.list) {
            this.getBelowList(res.list, 1);
          }
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    //获取其他类列表
    getOtherList() {
      this.listLoading = true;
      otherList({ store_id: this.formInline.store_id })
        .then(res => {
          if (res.list) {
            this.getBelowList(res.list, 1);
          }
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    //格式化列表
    getBelowList(list, type) {
      let totalMoney = 0;
      let totalTime = 0;
      for (let val of list) {
        if (type == 1 && val.time == 0) {
          continue;
        }
        this.belowList.push({
          name: val.name,
          money: val.money / 1,
          time: val.time / 1
        });
        totalMoney += val.money / 1;
        totalTime += val.time / 1;
      }
      if (totalMoney != 0) {
        this.belowList.forEach(val => {
          val.moneyRatio = ((val.money / totalMoney) * 100).toFixed(2) + '%';
        });
      } else {
        this.belowList.forEach(val => {
          val.moneyRatio = '-';
        });
      }
      if (totalTime != 0) {
        this.belowList.forEach(val => {
          val.timeRatio = ((val.time / totalTime) * 100).toFixed(2) + '%';
        });
      } else {
        this.belowList.forEach(val => {
          val.timeRatio = '-';
        });
      }
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 2 || index === 4) {
          sums[index] = '-';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          if (index === 3) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = (sums[index] * 1).toFixed(2);
          } else if (index === 1) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          }
        } else {
          sums[index] = '-';
        }
      });
      return sums;
    },
    //跳转营收汇总表
    jumpRevenueAnalysis_all_form() {
      this.$router.push({
        name: 'report/revenueAnalysis_all_form',
        params: { store_id: this.prevStoreId }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
div.customContainer {
  overflow-y: auto;
}
.chart-wrapper {
  background: #fff;
  padding: 15px;
  margin-bottom: 32px;
}
div.table-nav {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  div.nav-item {
    display: flex;
    justify-content: space-around;
    align-items: center;
    div {
      cursor: pointer;
      height: 32px;
      line-height: 32px;
      border-bottom: 2px solid transparent;
    }
    div.show {
      border-bottom: 2px solid #4892fb;
      color: #4892fb;
    }
  }
}
div.legend {
  z-index: 100;
  position: absolute;
  top: 2%;
  right: 10%;
  display: flex;
  font-size: 10px;
  color: #ccc;
}
div.legend div.legend-item {
  cursor: pointer;
  position: relative;
  display: flex;
  margin-left: 5px;
  div.legend-line {
    width: 26px;
    height: 5px;
    margin-right: 6px;
    border-bottom: 1px solid #ccc;
  }
  div.legend-circle {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    position: absolute;
    top: -1px;
    left: 7px;
    background: #fff;
    border: 1px solid #ccc;
  }
}
div.legend div.legend-fir {
  color: #000;
  div.legend-line {
    border-color: #5e9bdf;
  }
  div.legend-circle {
    border-color: #5e9bdf;
  }
}
div.legend div.legend-sec {
  color: #000;
  div.legend-line {
    border-color: #fdc927;
  }
  div.legend-circle {
    border-color: #fdc927;
  }
}
div.legend div.legend-thi {
  color: #000;
  div.legend-line {
    border-color: #ff4b4b;
  }
  div.legend-circle {
    border-color: #ff4b4b;
  }
}
div.legend div.disabled {
  cursor: no-drop;
}
</style> 